<template>
  <scroll-view
    class="messages-list"
    ref="messagesList"
    scroll-y
    :enable-flex="true"
    :show-scrollbar="true"
    :scroll-top="20"
    :scroll-into-view="lastMessageId"
  >
    <!-- 遍历消息列表 -->
    <div
      v-for="(msg, index) in messages"
      :key="index"
      :id="'message-' + index"
      :class="['message-wrapper', msg.sender == currentUser ? 'user-message' : 'other-message']"
    >
      <!-- 头像显示，长按头像时触发事件 -->
      <view @longtap="openOptionsMenu(msg.sender,msg.senderName)">
        <img
          :src="msg.avatar || defaultAvatar"
          alt="avatar"
          class="avatar"
          :class="{ 'avatar-right': msg.sender == currentUser }"
        />
      </view>

      <!-- 包装头像、用户名、消息框 -->
      <div class="message-container">
        <!-- 非当前用户显示用户名在消息框上方 -->
        <div v-if="msg.sender != currentUser" class="username">{{ msg.senderName }}</div>

        <!-- 消息内容 -->
        <div class="message-content">
          <span class="message-text">
            <span v-for="(part, partIndex) in parseMessage(msg.text)" :key="partIndex">
              <template v-if="part.isPhoneNumber">
                <a href="javascript:void(0)" @click="makePhoneCall(part.text)">
                  <span class="message-text" v-html="part.text"></span>
                </a>
              </template>
              <template v-else>
                <span class="message-text" v-html="part.text"></span>
              </template>
            </span>
          </span>
        </div>
      </div>
    </div>
  </scroll-view>
</template>

<script>
export default {
  name: "ChatMessages",
  props: {
    messages: {
      type: Array,
      required: true,
    },
    currentUser: {
      type: String,
      required: true,
    },
	pinID:{
		type:Number,
		required: true,
	}
  },
  data() {
    return {
      defaultAvatar: "https://cdn.builder.io/api/v1/image/assets/TEMP/default-avatar.png",
      lastMessageId: null,  // 用来追踪最后一条消息的 id
    };
  },
  watch: {
    // 监听消息数组变化，更新最后一条消息的 id
    messages: {
      handler() {
        this.lastMessageId = `message-${this.messages.length - 1}`;
      },
      immediate: true, // 初始时也需要触发
    },
  },
  methods: {
    // 解析消息内容，判断是否包含电话号码，并替换换行符
    parseMessage(message) {
      const phoneRegEx = /(\+?\d{1,4}[\s\-]?)?(\(?\d{2,3}\)?[\s\-]?)?(\d{4,5}[\s\-]?\d{4,5})/g;
      const parts = [];
      let lastIndex = 0;
      let match;

      while ((match = phoneRegEx.exec(message)) !== null) {
        if (match.index > lastIndex) {
          parts.push({ text: message.substring(lastIndex, match.index), isPhoneNumber: false });
        }
        parts.push({ text: match[0], isPhoneNumber: true });
        lastIndex = phoneRegEx.lastIndex;
      }
      
      if (lastIndex < message.length) {
        parts.push({ text: message.substring(lastIndex), isPhoneNumber: false });
      }

      parts.forEach(part => {
        if (!part.isPhoneNumber) {
          part.text = part.text.replace(/\n/g, '<br>');
        }
      });

      return parts;
    },
    // 使用uni-app的API拨打电话
    makePhoneCall(phoneNumber) {
      uni.makePhoneCall({
        phoneNumber: phoneNumber, // 要拨打的电话号码
        success() {
          console.log('拨打电话成功');
        },
        fail() {
          console.log('拨打电话失败');
        }
      });
    },
    // 长按头像时显示选项菜单，弹出是否投诉的确认框
    openOptionsMenu(sender,senderName) {
      uni.showModal({
        title: '投诉用户',
        content: `您确定要投诉用户 ${senderName} 吗？`,
        showCancel: true,
        cancelText: '取消',
        confirmText: '确定',
        success: (res) => {
          if (res.confirm) {
            // 如果用户点击了确定
            this.handleComplaint(sender);
			
          } else {
            // 用户点击了取消
			uni.showToast({
			  title: "投诉已取消",
			  icon: "none",
			});
            console.log('用户取消投诉');
          }
        },
        fail: (err) => {
          console.log('确认框失败', err);
        }
      });
    },
    // 处理投诉逻辑
    handleComplaint(sender) {
		uni.navigateTo({
		  url: `/pages/pinBranch/complaintPage?sender=${sender}&pinID=${this.pinID}`,
		});
      console.log(`投诉用户: ${sender}`);
	  
      // 在此处处理投诉逻辑，如将投诉信息发送到服务器
    }
  },
};
</script>

<style scoped>
.messages-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 10px;
  height: 100%;
  overflow-y: auto;
}

.message-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  max-width: 70%;
  justify-content: space-between;
  margin-bottom: 15px;
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.other-message {
  align-self: flex-start;
  flex-direction: row;
}

.message-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.avatar-right {
  margin-left: 10px;
}

.message-content {
  background-color: #000000;
  padding: 10px;
  border-radius: 10px;
  max-width: 200px;
}

.user-message .message-content {
  background-color: #ec5f5f;
  color: white;
}

.other-message .message-content {
  color: white;
}

.username {
  font-weight: bold;
  font-size: 0.9rem;
  margin-bottom: 5px;
  color: black;
}

.message-text {
  font-size: 1rem;
  margin-left: 0;
  user-select: text;
}
</style>
